package ink.xiaobaibai.filter;

import com.alibaba.fastjson.JSON;
import ink.xiaobaibai.response.ResponseFormat;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 分页验证拦截器
 * @author: 小白白
 * @create: 2021-05-23
 **/

public class PageValidFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        if (pageNumStr != null && !this.validPage(pageNumStr)) {
            this.fair(response);
            return;
        }
        if (pageSizeStr != null && !this.validPage(pageSizeStr)) {
            this.fair(response);
            return;
        }

        chain.doFilter(request, response);
    }

    private boolean validPage(String numStr) {
        if (numStr != null) {
            try {
                int pageSize = Integer.parseInt(numStr);
                if (pageSize <= 0) {
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    private void fair(ServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(ResponseFormat.fail("非法页码")));
    }


}
